﻿var socket;

var cancommand = false;

function connect(host, is_ex) {
    if (is_ex == undefined) {
        is_ex = false;
    }

    try {
        if (is_ex) 
        {
            socket = new WebSocketEx(host, "", onopen, onclose, onmessage, onerror);

        }
        else {
            socket = new WebSocket(host);

            socket.onopen = onopen;

            socket.onmessage = onmessage;

            socket.onclose = onclose;
            socket.onerror = onerror;
        }
//        message('<p class="event">Socket Status: ' + socket.readyState);

       

        return true;

    } catch (exception) {
        alert(exception);
        return false;
    }
} //End connect

function onclose() {
    //message('<p class="event">Socket Status: ' + socket.readyState + ' (closed) ' + new Date());
}

function onerror(e) {
    alert("error:" + e);
}

function onopen() {
    cancommand = true;
    //message('<p class="event">Socket Status: ' + socket.readyState + ' (open) ' + new Date());
}

function onmessage(msg) {
    var list = msg.data.split(" ");
    var com = list[0];
    var data = msg.data.substring(com.length).trim();
    try {
        var json_data = eval("(" + data + ")");
        eval(com + "_Command(json_data)");
    }
    catch (exception) {
        eval(com + "_Command(data)");
    }
}

function command(com, data) {
    if (!cancommand) {
        if (data == undefined) {
            setTimeout("command('"+com+"')", 100);
        }
        else {
            setTimeout("command('"+ com + "','" + data +"')", 100);
        }
        return;
    }

    if (data == undefined)
        send(com);
    else
        send(com + " " + data);
}

function send(msg) {
    try {
        if (socket != null) {
            socket.send(msg);
        }
    } catch (exception) {
        alert(exception);       
    }
}

function disconnect()
{
     try {
        if(socket != null)
        {
            socket.close();
        }
    } catch (exception) {
        alert(exception);       
    }
}

//function CONNECTED_Command(data) {
//    cancommand = true;
//}

String.prototype.trim = function () {
    var str = this.replace(/^(\s|\u00A0)+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

